<template>
  <div class="subscription-page ">
    <!-- 用户信息头部 -->
    <header class="header">
      <img :src="avatarUrl" class="avatar" alt="User Avatar" />
      <div class="user-info">
        <span class="username">{{ Username }}</span>
        <span class="user-status">购买后有效期将延长</span>
      </div>
    </header>

    <!-- 会员类型选择 -->
    <div class="membership-types">
      <el-tabs v-model="activeMembership" @tab-click="handleMembershipChange">
        <el-tab-pane label="普通会员" name="normal"></el-tab-pane>
        <el-tab-pane label="超级会员" name="super"></el-tab-pane>
      </el-tabs>
    </div>

    <!-- 订阅选项 -->
    <div class="subscription-options">
      <el-row :gutter="20">
        <el-col :xs="12" :sm="6" v-for="option in currentSubscriptionOptions" :key="option.duration">
          <el-card :class="{ 'selected': option.duration === selectedDuration }"
            @click="selectDuration(option.duration)">
            <div class="duration ">{{ option.duration }}</div>
            <div class="price">
              <span class="currency">¥</span>
              <span class="amount">{{ option.price }}</span>
            </div>
            <div v-if="option.originalPrice" class="original-price">
              <el-text type="info" tag="del">¥{{ option.originalPrice }}</el-text>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 总价和有效期 -->
    <div class="total-price">
      <span class="price-label">¥{{ currentPrice }}</span>
      <span class="validity">有效期至 {{ validityDate }}</span>
    </div>

    <!-- VIP权益展示 -->
    <div class="vip-benefits">
      <el-carousel :interval="4000" type="card" height="100px">
        <el-carousel-item v-for="item in currentVipBenefits" :key="item">
          <h3 class="benefit-item">{{ item }}</h3>

        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 会员兑换码支付 -->
    <div
      style="display: flex;justify-content: center; align-items: center; flex-direction:column;margin: 0 10px 0 10px;">
      <el-text class="mx-1" style="margin-right: auto;">会员兑换码支付</el-text>
      <div style="display: flex;justify-content: center; align-items: center; flex-direction:row;width: 100%;">
        <el-input v-model="secretKey" placeholder="请输入会员兑换码" />
        <el-button style="margin-left: 4px; width: 80px;" type="primary" @click="exchange">提交</el-button>
      </div>
    </div>

    <!-- 支付方式提示 -->
    <div class="payment-methods" style="text-align: center;">
      请使用支付宝进行支付
    </div>

    <!-- 二维码显示 -->
    <div class="qr-code">
      <img :src="qrCodeUrl" alt="QR Code" />
    </div>

    <!-- 服务协议同意 -->
    <div class="terms">

      <el-checkbox v-model="agreeTerms">开通即视为同意</el-checkbox>
      <el-link type="primary" @click="showTerms" style="margin-top: -12px;">《会员服务协议》</el-link>
    </div>
  </div>
</template>

<script lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import QRCode from 'qrcode';
import { GetBaseURL, DingDanModel, IDingDanModel } from '../../../src/composables/types'
import { getCookie, setCookie } from '../../../src/composables/utils'
import axios from 'axios';

export default {
  name: 'MembershipPurchase',
  // 修改 defineExpose 的写法
  expose: ['closeDialog'],
  setup() {
    const avatarUrl = ref('src/views/images/erweima.png')
    const activeMembership = ref('normal')
    const selectedDuration = ref('一年')
    const agreeTerms = ref(false)
    //二维码    
    const qrCodeUrl = ref('')
    const Username = ref('Youz')
    //Taken值
    const taken = ref('')
    //订单号
    const outTradeNo = ref('')
    // 使用ref创建一个响应式的引用，用于存储定时器的ID
    const intervalId = ref(null);
    // 使用ref创建一个响应式的引用，用于跟踪时间间隔
    const elapsedTime = ref(0);
    //会员兑换码
    const secretKey = ref('');

    const subscriptionOptions = {
      normal: [
        { duration: '一天', price: '5.80', originalPrice: '6.8' },
        { duration: '一个月', price: '28', originalPrice: '38' },
        { duration: '六个月', price: '68', originalPrice: '168' },
        { duration: '一年', price: '98', originalPrice: '298' },
      ],
      super: [
        { duration: '一个月', price: '38', originalPrice: '58' },
        { duration: '六个月', price: '98', originalPrice: '298' },
        { duration: '一年', price: '198', originalPrice: '598' },
      ]
    }

    const vipBenefits = {
      normal: ['解锁VIP', '对话模式', '多音纠读', '敏感词检测', '近义词替换'],
      super: ['所有普通会员特权', '高级AI模型', '无限使用次数', '优先客户支持']
    }

    const currentSubscriptionOptions = computed(() => subscriptionOptions[activeMembership.value])
    ///会员权益
    const currentVipBenefits = computed(() => vipBenefits[activeMembership.value])

    const currentPrice = computed(() => {
      const option = currentSubscriptionOptions.value.find(opt => opt.duration === selectedDuration.value)
      return option ? option.price : '0'
    })

    ///有效期
    const validityDate = computed(() => {
      const now = new Date()
      switch (selectedDuration.value) {
        case '一天': now.setDate(now.getDate() + 1); break
        case '一个月': now.setMonth(now.getMonth() + 1); break
        case '六个月': now.setMonth(now.getMonth() + 6); break
        case '一年': now.setFullYear(now.getFullYear() + 1); break
      }
      return now.toISOString().split('T')[0]
    })
    ///选择会员类型
    const handleMembershipChange = (tab) => {
      activeMembership.value = tab.props.name
      selectedDuration.value = currentSubscriptionOptions.value[0].duration
    }

    ///选择套餐
    const selectDuration = async (duration) => {
      const selectedOption = currentSubscriptionOptions.value.find(opt => opt.duration === duration);
      const membershipType = activeMembership.value === 'normal' ? '普通会员' : '超级会员';

      // successMessage(`已选择${membershipType} ${duration}套餐
      // 金额: ¥${selectedOption.price}
      // 用户: ${Username.value}
      // 有效期至: ${validityDate.value}`);

      // qrCodeUrl.value = 'src/views/images/erweima.png';
      selectedDuration.value = duration;

      //天数
      let days: string = "1";

      switch (duration) {
        case '一天': days = "1"; break
        case '一个月': days = "30"; break
        case '六个月': days = "180"; break
        case '一年': days = "365"; break
      }

      //发送请求生成订单并返回支付金额
      let dingdanmodel: DingDanModel = new DingDanModel();
      //金额
      dingdanmodel.amount = selectedOption.price;
      //支付类型，支付宝
      dingdanmodel.type = "alipay"; //支付类型，支付宝
      //标题
      dingdanmodel.title = membershipType;
      //用户名
      dingdanmodel.username = Username.value;
      //套餐id,这个需要从服务器上获取
      dingdanmodel.vipid = "1";
      //天数
      dingdanmodel.days = days;

      console.log('套餐dingdanmodel', dingdanmodel);

      //提交订单
      const response = await dingDanTiJiao(dingdanmodel);
      console.log('返回的订单信息', response.data);
      if (response.data.code == 1) {
        //返回的订单号
        outTradeNo.value = response.data.data.out_trade_no;
        console.log('返回的订单号', outTradeNo.value);
        // 启动支付返回定时器
        startPolling();
        //生成支付二维码
        await generateQRCode(response.data.data.qr_code);
      }
      else {
        errorMessage(response.data.msg);
      }
    }

    // 会员兑换码兑换
    const exchange = async () => {
      try {
        if (secretKey.value) {
          const response = await duiHuanDianQuan(secretKey.value);
          console.log('兑换结果', response.data);
          if (response.data.code == 1) {
            //兑换成功
            successMessage(response.data.msg);
          } else {
            //兑换失败
            errorMessage(response.data.msg);
          }
        }
      }
      catch (error) {
        errorMessage("兑换发生错误");
      }
    }

    // 生成二维码
    const generateQRCode = async (text: string) => {
      try {
        console.log('二维码URL', text);
        qrCodeUrl.value = await QRCode.toDataURL(text);
      } catch (error) {
        console.error('生成二维码时出错:', error);
      }
    }

    // 订单提交
    /**
     * 异步函数用于提交订单
     * 
     * 该函数负责将订单信息提交到服务器它使用axios库通过POST请求发送数据
     * 使用FormData对象来构造请求数据，包括支付类型、VIP等级、天数等信息
     * 
     * @param {DingDanModel} dingdanmodel - 订单模型，包含订单相关信息如支付类型、VIP等级和天数
     * @returns {Promise<any>} - 返回axios的响应对象
     */
    const dingDanTiJiao = async (dingdanmodel: DingDanModel) => {
      // 获取基础URL
      //const baseUrl: string = GetBaseURL();
      const baseUrl = "https://api.bishi.turuio.net";
      // 创建FormData对象用于构造表单数据
      const formData = new FormData();

      // 向formData中添加订单信息
      formData.append('paytype', dingdanmodel.type);
      formData.append('level', dingdanmodel.vipid);
      formData.append('days', dingdanmodel.days);
      formData.append('method', "scan");
      formData.append('openid', "");

      try {
        // 获取并设置token
        taken.value = getCookie("TR_token");
        // 使用axios发送POST请求提交订单
        const response = await axios.post(
          `${baseUrl}/addons/vip/api.order/submit`,
          formData,
          {
            headers: {
              'token': taken.value
            }
          }
        );
        // 返回响应对象
        return response;
      } catch (error) {
        // 捕获错误并打印到控制台
        console.error('Error错误捕捉:', error);
        // 抛出错误以便于调用者处理
        throw error;
      }
    }

    // 封装支付回调方法, 轮询调用
    /**
     * 支付回调函数
     * 该函数用于检查支付状态通过调用后端API进行查询
     * 
     * @param {string} tradeNo - 订单号，用于标识特定的交易
     * @returns {Promise<any>} - 返回后端API的响应结果
     */
    const zhiFuHuiDiao = async (tradeNo: string) => {
      // 获取基础URL，用于构建完整的API请求地址
      //const baseUrl: string = GetBaseURL();
      const baseUrl = "https://api.bishi.turuio.net";
      try {
        // 使用axios库发送POST请求检查支付状态
        const response = await axios.post(
          `${baseUrl}/api/photofix/pay/checkPaymentStatus`,
          {},
          {
            headers: {
              'out_trade_no': tradeNo
            }
          }
        );
        // 返回API的响应结果
        return response;
      } catch (error) {
        // 捕获错误并打印到控制台
        console.error('Error错误捕捉:', error);
        // 抛出错误，以便可以在函数调用链的更高层处理
        throw error;
      }
    }

    /**
     * 异步函数用于会员兑换码
     * @param {string} dmh - 卡密字符串，用于兑换点券
     * @returns {Promise<any>} - 返回axios请求的响应结果
     */
    const duiHuanDianQuan = async (dmh: string) => {
      // 获取基础URL，用于构建完整的API请求地址
      //const baseUrl: string = GetBaseURL();
      const baseUrl = "https://api.bishi.turuio.net";
      // 创建FormData对象用于构造表单数据
      const formData = new FormData();
      // 添加卡密
      formData.append('card', dmh);
      // 获取并设置token
      taken.value = getCookie("TR_token");
      console.log('taken.value',taken.value);

      try {
        // 使用axios库发送POST请求检查支付状态
        const response = await axios.post(
          `${baseUrl}/addons/vip/api.order/cardPay`,
          {
            headers: {
              'token': taken.value
            },
            data: formData
          }
        );
        // 返回API的响应结果
        return response;
      } catch (error) {
        // 捕获错误并打印到控制台
        console.error('Error错误捕捉:', error);
        // 抛出错误，以便可以在函数调用链的更高层处理
        throw error;
      }
    }

    // 启动定时器的方法
    const startPolling = () => {
      // 清除之前的定时器（如果有）
      clearInterval(intervalId.value);

      // 重置经过的时间
      elapsedTime.value = 0;

      // 设置新的定时器
      intervalId.value = setInterval(async () => {
        // 累加经过的时间
        elapsedTime.value += 500;
        try {
          // 调用支付回调函数
          if (outTradeNo.value == undefined || outTradeNo.value == "" || outTradeNo.value == null) {
            //没有订单号不执行
            return;
          }
          else {
            // 如果等待时间超过两分钟，则清除定时器
            if (elapsedTime.value >= 120000) {
              clearInterval(intervalId.value);
              errorMessage("超过支付的有效时间了,请重新下单");
              return;
            }

            const result = await zhiFuHuiDiao(outTradeNo.value);

            if (result.data.code === 1) {
              successMessage('支付成功');
              clearInterval(intervalId.value);
              return;
            }
            // 如果回调结果成功或等待时间超过两分钟，则清除定时器
            if (result.data.code === 1 || elapsedTime.value >= 120000) {
              clearInterval(intervalId.value);
              console.log('退出条件满足，停止调用zhiFuHuiDiao方法。');
              return;
            }
          }
        } catch (error) {
          // 捕获并输出调用支付回调函数时的错误
          //console.error('定时器调用zhiFuHuiDiao时出错:', error);
        }
      }, 500);
    };

    ///封装成功提示 
    const successMessage = (value) => {
      ElMessage({
        message: value,
        type: 'success',
      })
    }
    ///封装错误提示 
    const errorMessage = (value) => {
      ElMessage.error(value)
    }

    ///会员服务协议
    const showTerms = () => {
      ElMessageBox.alert('这里是会员服务协议的内容...', '会员服务协议', {
        confirmButtonText: '我已阅读并同意',
        callback: (action) => {
          if (action === 'confirm') {
            agreeTerms.value = true
          }
        }
      })
    }

    /**
     * 初始化函数
     * 用于在组件加载时获取用户数据并更新组件状态
     */
    const initialize = async () => {
      try {
        // 模拟API请求
        // const response = await fetch('https://api.example.com/user-data')
        // const userData = await response.json()

        // 使用模拟数据
        const userData = {
          username: 'Youz',
          avatarUrl: 'src/views/images/erweima.png',
          membershipType: 'normal'
        }

        // 更新组件状态
        //取用户名称
        const savedUsername = getCookie('TR_username');
        Username.value = savedUsername;

        //取用户头像
        const savedAvatarUrl = getCookie("TR_vatar");
        avatarUrl.value = userData.avatarUrl

        activeMembership.value = userData.membershipType

        //取用户token
        taken.value = getCookie("TR_token");

        // 显示成功消息
        successMessage('数据加载成功')
      } catch (error) {
        // 显示错误消息
        errorMessage('数据加载失败: ' + error.message)
      }
    }

    ///关闭对话框,清除定时器
    function closeDialog(){
      if (intervalId.value) {
        clearInterval(intervalId.value);
      }
    }

    ///初始化
    // 当组件挂载时执行以下函数
    onMounted(() => {
      // 初始化某些操作
      initialize();
    });

    // 组件卸载时清除定时器
    onBeforeUnmount(() => {
      closeDialog();
    });

    return {
      avatarUrl,
      activeMembership,
      selectedDuration,
      agreeTerms,
      qrCodeUrl,
      Username,
      currentSubscriptionOptions,
      currentVipBenefits,
      currentPrice,
      validityDate,
      handleMembershipChange,
      selectDuration,
      successMessage,
      errorMessage,
      showTerms,
      initialize,
      taken,
      intervalId,
      elapsedTime,
      secretKey,
      duiHuanDianQuan,
      exchange,
      closeDialog
    }
  }
}
</script>

<style scoped>
.subscription-page {

  max-width: 600px;
  margin: 0 auto;
  font-family: Arial, sans-serif;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 10px;
}

.user-info {
  flex-grow: 1;
}

.username {
  font-weight: bold;
  display: block;
}

.user-status {
  font-size: 0.9em;
  color: #666;
}

.close-icon {
  cursor: pointer;
}

.membership-types {
  margin-bottom: 10px;
}

.membership-icon {
  width: 30px;
  height: 30px;
  margin-right: 5px;
}

.subscription-options .el-card {
  text-align: center;
  cursor: pointer;
  margin-bottom: 10px;
}

.subscription-options .el-card.selected {
  border-color: transparent;
  background-color: #FFD700;
}

.duration {
  font-weight: bold;
}

.price {
  font-size: 1.2em;
  color: #ff4500;
  margin: 5px 0;
}

.original-price {
  font-size: 0.9em;
}

.total-price {
  text-align: right;
  margin: 10px 0;
}

.price-label {
  font-size: 1.5em;
  font-weight: bold;
  color: #ff4500;
}

.validity {
  font-size: 0.9em;
  color: #666;
  margin-left: 10px;
}

.vip-benefits {
  margin: 10px 0;
}

.benefit-item {
  color: #333;
  font-size: 14px;
  line-height: 100px;
  margin: 0;
  text-align: center;
}

.payment-methods {
  margin: 20px 0;
}

.payment-icon {
  width: 20px;
  height: 20px;
  margin-right: 5px;
  vertical-align: middle;
}

.qr-code {
  text-align: center;
  margin: 20px 0;
}

.qr-code img {
  width: 150px;
  height: 150px;
}

.terms {
  text-align: center;
  font-size: 0.9em;
}
</style>